package com.ja.openchat.ui.chat.group;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityGroupRestrictedListBinding;
import com.ja.openchat.ui.contact.ContactListAdapter;
import com.ja.openchat.viewmodels.GroupRestrictedViewModel;
import com.ja.openchat.views.SideIndexBar;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.DensityUtil;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class GroupRestrictedListActivity extends BaseActivity<ActivityGroupRestrictedListBinding,GroupRestrictedViewModel> {
    private ContactListAdapter contactListAdapter;
    private List<Section> sectionList = new ArrayList<>();

    private ChatInfo chatInfo;

    //创建侧滑菜单
    private final SwipeMenuCreator creator = (leftMenu, rightMenu, position) -> {
        Section sec = sectionList.get(position);
        if (!sec.isHeader()) {
            SwipeMenuItem delItem = new SwipeMenuItem(this)
                    .setBackgroundColorResource(R.color.red8)
                    .setImage(R.mipmap.icon_close)
                    .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                    .setWidth(DensityUtil.dp2px(65));
            rightMenu.addMenuItem(delItem);
        }
    };

    public static void start(Activity activity, ChatInfo chat) {
        Intent intent = new Intent();
        intent.setClass(activity, GroupRestrictedListActivity.class);
        intent.putExtra("chat", chat);
        activity.startActivity(intent);
    }
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_group_restricted_list;
    }


    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public GroupRestrictedViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(GroupRestrictedViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.toolbar.tvBarTitle.setText(getString(R.string.banned_members_list));
        if (getIntent() != null) {
            chatInfo = getIntent().getParcelableExtra("chat");
        } else {
            chatInfo = new ChatInfo();
        }
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //初始化列表
        initListUI();
        //加载数据
        reloadContacts(new ArrayList<>());
        reloadGroupRtdMembers();
        //索引事件
        binding.slide.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        binding.recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
    }

    private void initListUI() {
        //初始化列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        //设置侧滑菜单列表
        binding.recyclerView.setSwipeMenuCreator(creator);
        //侧滑事件监听回调
        binding.recyclerView.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            switch (menuBridge.getPosition()) {
                case 0:
                    menuBridge.closeMenu();
                    unbanMember((UserInfo) sectionList.get(adapterPosition).getObject());
                    break;
            }
        });

        contactListAdapter = new ContactListAdapter(R.layout.adapter_contact_list, R.layout.adapter_section_contact_list, sectionList);
        binding.recyclerView.setAdapter(contactListAdapter);
    }

    private void reloadGroupRtdMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(this,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterRestricted", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    List<UserInfo> list = new ArrayList<>();
                    for (GroupMemberInfo member : obj) {
                        UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
                        if (user != null) {
                            list.add(user);
                        }
                    }
                    reloadContacts(list);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void reloadContacts(List<UserInfo> list) {
        sectionList.clear();
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        //生成a-z hash
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : binding.slide.DEFAULT_INDEX_ITEMS) {
            sectionMap.put(azIndex, new ArrayList<>());
        }
        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : binding.slide.DEFAULT_INDEX_ITEMS) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    sectionList.add(new Section(false, user));
                }
            }
        }
        //刷新页面
        contactListAdapter.notifyDataSetChanged();
    }

    private void unbanMember(UserInfo user) {
        showProgress();
        TelegramManager.getTelegramManager().banMemberFromSuperGroup(this, chatInfo.id, user.id, false, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    reloadGroupRtdMembers();
                    showErrorTip(getString(R.string.unmuted_text));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }
}